package com.haoxin.ai_course.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.haoxin.ai_course.common.base.AbstractController;
import com.haoxin.ai_course.common.utils.Constant;
import com.haoxin.ai_course.common.utils.HttpUtil;
import com.haoxin.ai_course.common.utils.R;
import com.haoxin.ai_course.modules.sys.entity.SysUser;
import com.haoxin.ai_course.modules.sys.service.SysUserService;
import com.haoxin.ai_course.modules.sys.service.SysUserTokenService;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@AllArgsConstructor
//@Api (value="api",tags="登录相关接口")
@Api (value="api", hidden=true)
public class SysLoginController extends AbstractController {

	private final Producer producer;
	private final SysUserService sysUserService;
	private final SysUserTokenService sysUserTokenService;
	private final RedisTemplate redisTemplate;

	/**
	 * 验证码
	 */
	@SneakyThrows
	@RequestMapping("/sys/code/{time}")
	public void captcha(@PathVariable("time") String time, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字验证码
		String text = producer.createText();
		log.info("==================验证码:{}====================", text);
		// 生成图片验证码
		BufferedImage image = producer.createImage(text);
		// redis 60秒
		redisTemplate.opsForValue().set(Constant.NUMBER_CODE_KEY + time, text, 60, TimeUnit.SECONDS);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 短信验证码
	 */
	@RequestMapping("/mobile/code/{number}")
	public Map<String, Object> mobile(@PathVariable("number") String number) {

		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mobile", number);
		SysUser user = sysUserService.getOne(queryWrapper);

		// 账号不存在
		if (user == null) {
			return R.error("手机号码未注册");
		}

		String mobile = (String) redisTemplate.opsForValue().get(Constant.MOBILE_CODE_KEY + number);
		if (!StrUtil.isEmpty(mobile)) {
			return R.error("验证码未失效");
		}

		// 生成4位验证码
		String code = RandomUtil.randomNumbers(Constant.CODE_SIZE);
		log.info("==================短信验证码:{}====================", code);
		// redis 60秒
		redisTemplate.opsForValue().set(Constant.MOBILE_CODE_KEY + number, code, 60, TimeUnit.SECONDS);
		// 调用短信服务去发送

		return R.ok("验证码发送成功");
	}

	/**
	 * 密码登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(HttpServletRequest httpServletRequest, String username, String password) {
		if (username == null) {
			Map<String, String> o = commonHttpRequestParamConvert(httpServletRequest);
			username = o.get("username");
			password = o.get("password");
		}
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return R.error("请填写账号或密码");
		}
		// 创建查询条件
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//		用户名等于用户输入的用户名
		queryWrapper.eq("username", username);
//		获取用户记录
		SysUser user = sysUserService.getOne(queryWrapper);
//		两个数相减得到剩余毫秒数 除以1000 得到秒数  除以60 得到分钟数 除以60得到小时数
		String inputPassword = new Sha256Hash(password, user.getSalt()).toHex();
//		如果剩余毫秒数
		// 账号不存在、密码错误
		if (user == null || user.getPassword() == null
				|| !user.getPassword().equals(inputPassword)) {
			return R.error("账号或密码不正确");
		}

		// 账号锁定
		if (user.getStatus() == 0) {
			return R.error("账号已被锁定,请联系管理员");
		}
		R r = sysUserTokenService.createToken(user.getUserId());

		return r;
	}

	/**
	 * 手机号码登录
	 */
	@RequestMapping(value = "/mobile/login", method = RequestMethod.POST)
	public Map<String, Object> mobileLogin(String mobile, String code) {

		String code_key = (String) redisTemplate.opsForValue().get(Constant.MOBILE_CODE_KEY + mobile);
		if (StrUtil.isEmpty(code_key)) {
			return R.error("验证码过期");
		}

		if (!code.equalsIgnoreCase(code_key)) {
			return R.error("验证码不正确");
		}

		// 用户信息
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mobile", mobile);
		SysUser user = sysUserService.getOne(queryWrapper);

		// 账号不存在
		if (user == null) {
			return R.error("账号不存在");
		}

		// 账号锁定
		if (user.getStatus() == 0) {
			return R.error("账号已被锁定,请联系管理员");
		}

		// 生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/sys/logout", method = RequestMethod.POST)
	public R logout() {
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}

	/**
	 * 未认证
	 */
	@RequestMapping(value = "/sys/unauthorized", method = RequestMethod.POST)
	public R unauthorized() {
		return R.error(HttpStatus.SC_UNAUTHORIZED, "unauthorized");
	}
	
	/**
	 * 通用请求格式转换
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	public Map<String, String> commonHttpRequestParamConvert(HttpServletRequest httpServletRequest) {
		Map<String, String> params = new HashMap<>();
		try {
			Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
			if (requestParams != null && !requestParams.isEmpty()) {
				requestParams.forEach((key, value) -> params.put(key, value[0]));
			} else {
				StringBuilder paramSb = new StringBuilder();
				try {
					String str = "";
					BufferedReader br = httpServletRequest.getReader();
					while ((str = br.readLine()) != null) {
						paramSb.append(str);
					}
				} catch (Exception e) {
					System.out.println("httpServletRequest get requestbody error, cause : " + e);
				}
				if (paramSb.length() > 0) {
					JSONObject paramJsonObject = JSON.parseObject(paramSb.toString());
					if (paramJsonObject != null && !paramJsonObject.isEmpty()) {
						paramJsonObject.forEach((key, value) -> params.put(key, String.valueOf(value)));
					}
				}
			}
		} catch (Exception e) {
			System.out.println("commonHttpRequestParamConvert error, cause : " + e);
		}
		return params;
	}
	public static void main(String[] args) {
//		AppSecret(小程序密钥)
//		4f2eea1971f4db188e2bc4de12bfc538 
//		AppID(小程序ID) 
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxa4bf6d70731b872f&secret=wxa4bf6d70731b872f&js_code=031qtzll2DWMT84zb5ml2gWFCl0qtzlL&grant_type=authorization_code";
//		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxa4bf6d70731b872f&secret=4f2eea1971f4db188e2bc4de12bfc538&js_code=031qtzll2DWMT84zb5ml2gWFCl0qtzlL&grant_type=authorization_code";
//		 HttpJsonResult<DoctorInfoResp> result = getUserInfoByWechat("wxa4bf6d70731b872f", "wxa4bf6d70731b872f", "031qtzll2DWMT84zb5ml2gWFCl0qtzlL");
		String result = HttpUtil.doGet(url, "");
//		JSONObject jsonResult = JSONObject.parseObject(result);
		System.out.println( result);
//		System.out.println( result);
	}
}
